<template>
  <div style="display: flex; justify-content: center; align-items: center; width: 100%; height: 24px; font-weight: bold; font-size: 24px; margin-top: 24px;">
    维修上传
  </div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="taskId" label="任务ID" />
    <el-table-column prop="acceptanceTime" label="任务接受时间" />
    <el-table-column label="上传进度">
      <template #default="scope">
        <el-button v-if="scope.row.taskId" type="primary" @click="showProgressDialog(scope.$index)">上传</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
      v-model="progressDialogVisible"
      title="上传维修照片"
      width="90%"
      :style="{ height: dialogHeight }"
  >
    <el-upload
        action="http://localhost:8080/upload"
        list-type="picture-card"
        :auto-upload="false"
        :file-list="fileList"
        @remove="handleRemove"
        @preview="handlePreview"
        @change="handleFileChange"
    >
      <i class="el-icon-picture-outline"></i>
      <div class="el-upload__text">添加图片</div>
    </el-upload>
    <el-dialog v-model="dialogVisible" width="80%" title="预览图片">
      <img class="preview-image" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="progressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadAndClose">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <div class="bottom-fixed-button">
    <el-button type="primary" style="width: 90%; " @click="returnToTechnician">返回菜单</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import {ElButton, ElMessage} from 'element-plus';
import axios from "axios";
import {useStore} from "vuex";
import {useRouter} from "vue-router";

const fileList = ref([] as { file: File, name: string, status: string }[]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const tableData = ref([]);
const progressDialogVisible = ref(false);
const progressInput = ref('');
const dialogHeight = computed(() => `${window.innerHeight * 0.8}px`);


const router=useRouter();
const returnToTechnician = () =>{
  router.push('/technician/home')
}

const store = useStore();

onMounted(async () => {
  try {
    const user = store.getters.user;
    if (!user || !user.repairPersonnelId) {
      ElMessage.error('用户未登录或用户信息不完整');
      return;
    }

    const response = await axios.get(`http://localhost:8080/repair-tasks/set/${user.repairPersonnelId}`);
    if (response.status === 200) {
      tableData.value = [response.data];
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
});

const handleRemove = (file: { file: File, name: string, status: string }) => {
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
};

const handlePreview = (file: { url: string }) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleFileChange = (file: { raw: File, name: string }) => {
  const newFile = { file: file.raw, name: file.name, status: 'ready' };
  fileList.value.push(newFile);
};

const uploadAndClose = async () => {
  const formData = new FormData();
  fileList.value.forEach(file => formData.append('files', file.file, file.name));
  try {
    const response = await fetch('http://localhost:8080/repair-tasks/upload/1', {
      method: 'POST',
      body: formData,
    });

    if (response.ok) {
      const data = await response.json();
      ElMessage.success(`照片上传成功: ${data.message}`);
      updateProgressAndClose();
    } else {
      ElMessage.error('照片上传失败');
    }
  } catch (error) {
    ElMessage.error('照片上传失败');
  }
};

const updateProgressAndClose = async () => {
  const selectedRowId = 1; // 假设要更新的是 ID 为 1 的行
  // 更新前端表格数据（假设这里是 Vue.js 的响应式数据）
  tableData.value[selectedRowId - 1].status = progressInput.value;

  // 关闭进度对话框
  progressDialogVisible.value = false;

  // 执行 HTTP GET 请求来触发后端操作
  /*try {
    const response = await fetch(`http://localhost:8080/repair-tasks/up/${selectedRowId}`);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    console.log('请求成功'); // 请求成功的处理
  } catch (error) {
    console.error('请求失败:', error); // 请求失败的处理
  }*/

  try {
    const response = await fetch(`http://localhost:8080/maintenance-records/up/${selectedRowId}`);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    console.log('请求成功'); // 请求成功的处理
  } catch (error) {
    console.error('请求失败:', error); // 请求失败的处理
  }
};

const showProgressDialog = (index) => {
  progressDialogVisible.value = true;
};
</script>

<style scoped>
.preview-image {
  max-width: 100%;
  max-height: 100%;
}
.bottom-fixed-button {
  height: 50px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  z-index: 1000;
  justify-content: center;
  align-items: center;
  padding-bottom: 10px;
}
</style>